<template>
  <div class="search-suggestion">
    <van-cell
      icon="search"
      v-for="(item, index) in list"
      :key="index"
      @click="$emit('search', item)"
    >
      <div v-html="highlight(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from "@/api/search";
// lodash 支持按需加载，有利于打包结果优化
import { debounce } from "lodash";
export default {
  name: "SearchSuggestion",
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    };
  },
  computed: {},
  watch: {
    searchText: {
      // 第一次就执行
      immediate: true,
      async handler() {
        this.loadSearch();
      }
    }
  },
  created() {},
  mounted() {},
  methods: {
    loadSearch: debounce(async function() {
      try {
        let { data: res } = await getSearchSuggestion(this.searchText);
        this.list = res.data.options;
      } catch (error) {
        this.$toast.fail("获取联想建议失败");
      }
    }, 1000),
    // 处理样式的高亮效果
    highlight(val) {
      const reg = new RegExp(this.searchText, "gi");
      return val.replace(
        reg,
        `<span style="color: red">${this.searchText}</span>`
      );
    }
  }
};
</script>

<style scoped lang="less"></style>
